package com.neusoft.hifly.dictionary.dict.service.impl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LongUtil;
import com.neusoft.hifly.commons.lang.StringConstants;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.annotation.LogType;
import com.neusoft.hifly.core.log.annotation.OperationLog;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.dictionary.dict.dao.IDictionaryGroupDao;
import com.neusoft.hifly.dictionary.dict.entity.DictionaryGroupObj;
import com.neusoft.hifly.dictionary.dict.service.IDictionaryGroupService;
import com.neusoft.hifly.dynamicds.multi.annotation.MultiDynamicRoutingDataSource;

/**
 * Title: 数据字典服务
 * <p>
 * Description: 数据字典组 Service
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
@MultiDynamicRoutingDataSource
public class DictionaryGroupServiceImpl extends CTSaaSBaseServiceImpl implements IDictionaryGroupService {
	@Autowired(required = false)
	private IDictionaryGroupDao dictionaryGroupDao;

	/**
	 * 保存对象
	 *
	 * @param obj
	 *            对象
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	@CacheEvict(value = "dic:dictgroup", allEntries = true)
	@OperationLog(method = LogType.UPDATE, msg = "数据字典组")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void saveOrUpdate(final DictionaryGroupObj obj) throws SystemErrorException {
		if (obj == null) {
			return;
		}

		final String name = StringUtils.trimToEmpty(obj.getName());
		if (StringUtils.isEmpty(name)) {
			throw new SystemErrorException("名称不能为空!");
		}

		final String code = StringUtils.trimToEmpty(obj.getCode());
		if (StringUtils.isEmpty(code)) {
			throw new SystemErrorException("编码不能为空!");
		}

		final DictionaryGroupObj oldObj = dictionaryGroupDao.getByLogicId(obj.getLogicId());

		// 有ID的话要判断是否保存还是更新
		if (oldObj == null) {
			// 保存

			if (null != this.getByName(name)) {
				throw new SystemErrorException("名称 [ " + name + " ] 已存在!");
			}

			if (null != this.getByCode(code)) {
				throw new SystemErrorException("编码 [ " + name + " ] 已存在!");
			}

			obj.setId(idWorker.nextId());
			if (LongUtil.isEmpty(obj.getLogicId())) {
				obj.setLogicId(idWorker.nextId());
			}
			obj.setUpdateTime(LocalDateTime.now());

			if (StringUtils.isEmpty(obj.getUpdatePerson())) {
				obj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			this.setForm(obj, obj);

			dictionaryGroupDao.insert(obj);

		} else {
			// 更新
			if (!StringUtils.equals(oldObj.getName(), name)) {
				if (null != this.getByName(name)) {
					throw new SystemErrorException("名称 [ " + name + " ] 已存在!");
				}
			}
			if (!StringUtils.equals(oldObj.getCode(), code)) {
				if (null != this.getByCode(code)) {
					throw new SystemErrorException("编码 [ " + code + " ] 已存在!");
				}
			}

			this.setForm(obj, oldObj);

			oldObj.setUpdateTime(LocalDateTime.now());
			if (StringUtils.isEmpty(oldObj.getUpdatePerson())) {
				oldObj.setUpdatePerson(TokenContextHolder.get().getUserName());
			}

			dictionaryGroupDao.updateById(oldObj);

		}
	}

	/**
	 * 根据ID删除对象
	 *
	 * @param logicId
	 *            对象ID
	 */
	@Override
	@CacheEvict(value = "dic:dictgroup", allEntries = true)
	@OperationLog(method = LogType.DELETE, msg = "数据字典组")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class, RuntimeException.class })
	public void deleteByLogicId(final long logicId) {
		dictionaryGroupDao.deleteByLogicId(logicId);
	}

	/**
	 * 批量删除对象
	 *
	 * @param logicIds
	 *            对象ID，多id使用英文逗号分隔
	 */
	@Override
	public void deleteByBatch(final String logicIds) {
		if (StringUtils.isEmpty(logicIds)) {
			return;
		}
		final String[] logicIdArr = logicIds.split(StringConstants.STRING_SPLIT_FLAG_3);
		if (logicIdArr == null) {
			return;
		}
		for (final String logicId : logicIdArr) {
			if (StringUtils.isEmpty(logicId)) {
				continue;
			}
			this.deleteByLogicId(Long.parseLong(logicId));
		}
	}

	/**
	 * 根据id查询对象
	 *
	 * @param logicId
	 *            对象logicId
	 * @return 对象
	 */
	@Override
	@Cacheable(value = "dic:dictgroup")
	public DictionaryGroupObj getByLogicId(final long logicId) {
		return dictionaryGroupDao.getByLogicId(logicId);
	}

	/**
	 * 根据名称查询对象
	 *
	 * @param name
	 *            名称
	 * @return 对象
	 */
	@Override
	public DictionaryGroupObj getByName(final String name) {
		if (StringUtils.isEmpty(name)) {
			return null;
		}
		final List<DictionaryGroupObj> list = dictionaryGroupDao.findByName(name);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * 根据编码查询对象
	 *
	 * @param code
	 *            编码
	 * @return 对象
	 */
	@Override
	@Cacheable(value = "dic:dictgroup")
	public DictionaryGroupObj getByCode(final String code) {
		if (StringUtils.isEmpty(code)) {
			return null;
		}
		final List<DictionaryGroupObj> list = dictionaryGroupDao.findByCode(code);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	/**
	 * 查询所有对象
	 *
	 * @return 对象集合
	 */
	@Override
	@Cacheable(value = "dic:dictgroup")
	public List<DictionaryGroupObj> findAll() {
		return dictionaryGroupDao.findAll();
	}

	/**
	 * 根据条件查询
	 *
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 集合
	 */
	@Override
	public List<DictionaryGroupObj> search(final Map<String, Object> property) {
		final QueryWrapper<DictionaryGroupObj> queryWrapper = new QueryWrapper<DictionaryGroupObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "GROUP_ORDER", "UPDATE_TIME" });
		return dictionaryGroupDao.selectList(queryWrapper);
	}

	/**
	 * 根据条件查询
	 *
	 * @param offset
	 *            当前页数
	 * @param limit
	 *            分页长度
	 * @param property
	 *            参数。其中isLike:Boolean 是否模糊查询
	 * @return 返回Map
	 */
	@Override
	public IPage<DictionaryGroupObj> search(final int offset, final int limit, final Map<String, Object> property) {
		final IPage<DictionaryGroupObj> page = new Page<DictionaryGroupObj>(offset, limit);
		final QueryWrapper<DictionaryGroupObj> queryWrapper = new QueryWrapper<DictionaryGroupObj>();
		replaceProperty(property);
		createSql(property, queryWrapper, new String[] { "GROUP_ORDER", "UPDATE_TIME" });
		return dictionaryGroupDao.selectPage(page, queryWrapper);
	}

	/**
	 * 复制信息
	 *
	 * @param fromObj
	 *            原信息
	 * @param toObj
	 *            新信息
	 */
	private void setForm(final DictionaryGroupObj fromObj, final DictionaryGroupObj toObj) {
		toObj.setName(StringUtils.trimToEmpty(fromObj.getName()));
		toObj.setCode(StringUtils.trimToEmpty(fromObj.getCode()));
		toObj.setShowOption(StringUtils.trimToEmpty(fromObj.getShowOption()));
		toObj.setMyOrder(fromObj.getMyOrder());
		toObj.setMemo(StringUtils.trimToEmpty(fromObj.getMemo()));
		toObj.setExt1(StringUtils.trimToEmpty(fromObj.getExt1()));
		toObj.setExt2(StringUtils.trimToEmpty(fromObj.getExt2()));
		toObj.setExt3(StringUtils.trimToEmpty(fromObj.getExt3()));
		toObj.setExt4(StringUtils.trimToEmpty(fromObj.getExt4()));
		toObj.setExt5(StringUtils.trimToEmpty(fromObj.getExt5()));

	}

	/**
	 * 将对象属性替换成数据库列
	 *
	 * @param property
	 *            参数
	 */
	private void replaceProperty(final Map<String, Object> property) {
		if (property != null) {
			if (property.containsKey("name")) {
				property.put("GROUP_NAME", property.get("name"));
				property.remove("name");
			}
			if (property.containsKey("code")) {
				property.put("GROUP_CODE", property.get("code"));
				property.remove("code");
			}
			if (property.containsKey("showOption")) {
				property.put("GROUP_OPTION", property.get("showOption"));
				property.remove("showOption");
			}
			if (property.containsKey("myOrder")) {
				property.put("GROUP_ORDER", property.get("myOrder"));
				property.remove("myOrder");
			}
			if (property.containsKey("memo")) {
				property.put("GROUP_MEMO", property.get("memo"));
				property.remove("memo");
			}
			if (property.containsKey("updatePerson")) {
				property.put("UPDATE_PERSON", property.get("updatePerson"));
				property.remove("updatePerson");
			}
			if (property.containsKey("updateTime")) {
				property.put("UPDATE_TIME", property.get("updateTime"));
				property.remove("updateTime");
			}
			if (property.containsKey("ext1")) {
				property.put("EXT1", property.get("ext1"));
				property.remove("ext1");
			}
			if (property.containsKey("ext2")) {
				property.put("EXT2", property.get("ext2"));
				property.remove("ext2");
			}
			if (property.containsKey("ext3")) {
				property.put("EXT3", property.get("ext3"));
				property.remove("ext3");
			}
			if (property.containsKey("ext4")) {
				property.put("EXT4", property.get("ext4"));
				property.remove("ext4");
			}
			if (property.containsKey("ext5")) {
				property.put("EXT5", property.get("ext5"));
				property.remove("ext5");
			}

		}
	}
}